package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.QualificationManagement;
import com.ruoyi.system.domain.ScoreManagement;
import com.ruoyi.system.service.IQualificationManagementService;
import com.ruoyi.system.service.IIdentityManagementService;
import com.ruoyi.system.service.IDbQualificationManagementService;
import com.ruoyi.system.service.IScoreManagementService;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Validator;
import java.util.stream.Collectors;

import com.ruoyi.system.domain.dto.StatisticsDTO;
import com.ruoyi.system.domain.dto.StatisticsDTO.PositionData;

/**
 * 四级联考资格审查Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class QualificationManagementServiceImpl implements IQualificationManagementService 
{
    private static final Logger log = LoggerFactory.getLogger(QualificationManagementServiceImpl.class);

    @Autowired
    private QualificationManagementMapper qualificationManagementMapper;

    @Autowired
    private ResultManagementMapper resultManagementMapper;

    @Autowired
    private DbPhysicalManagementMapper dbPhysicalManagementMapper;

    @Autowired
    private DbIdentityManagementMapper dbIdentityManagementMapper;

    @Autowired
    private DbQualificationManagementMapper dbQualificationManagementMapper;

    @Autowired
    private PhysicalManagementMapper physicalManagementMapper;

    @Autowired
    private IdentityManagementMapper identityManagementMapper;

    
    @Autowired
    protected Validator validator;
    
    @Autowired
    private IIdentityManagementService identityManagementService;
    
    @Autowired
    private IDbQualificationManagementService dbQualificationManagementService;
    
    @Autowired
    private IScoreManagementService scoreManagementService;

    /**
     * 查询四级联考资格审查
     * 
     * @param id 四级联考资格审查主键
     * @return 四级联考资格审查
     */
    @Override
    public QualificationManagement selectQualificationManagementById(Long id)
    {
        return qualificationManagementMapper.selectQualificationManagementById(id);
    }

    /**
     * 查询四级联考资格审查列表
     * 
     * @param qualificationManagement 四级联考资格审查
     * @return 四级联考资格审查
     */
    @Override
    public List<QualificationManagement> selectQualificationManagementList(QualificationManagement qualificationManagement)
    {
        return qualificationManagementMapper.selectQualificationManagementList(qualificationManagement);
    }

    /**
     * 新增四级联考资格审查
     * 
     * @param qualificationManagement 四级联考资格审查
     * @return 结果
     */
    @Override
    public int insertQualificationManagement(QualificationManagement qualificationManagement)
    {
        return qualificationManagementMapper.insertQualificationManagement(qualificationManagement);
    }

    /**
     * 修改四级联考资格审查
     * 
     * @param qualificationManagement 四级联考资格审查
     * @return 结果
     */
    @Override
    @Transactional
    public int updateQualificationManagement(QualificationManagement qualificationManagement)
    {
        // 获取修改前的资格审查信息
        QualificationManagement originalData = qualificationManagementMapper.selectQualificationManagementById(qualificationManagement.getId());
        
        // 执行更新操作
        int rows = qualificationManagementMapper.updateQualificationManagement(qualificationManagement);
        
        // 检查是否成功更新，并且是否将资格审查结果修改为"通过"
        if (rows > 0 && "通过".equals(qualificationManagement.getQualificationReviewResult()) 
            && (originalData == null || !"通过".equals(originalData.getQualificationReviewResult())))
        {
            try
            {
                // 获取完整的修改后数据
                QualificationManagement updatedData = qualificationManagementMapper.selectQualificationManagementById(qualificationManagement.getId());
                
                // 创建临时列表用于流转
                List<QualificationManagement> tempList = new java.util.ArrayList<>();
                tempList.add(updatedData);
                
                // 调用身份验证服务，将该考生数据流转到身份验证模块
                identityManagementService.insertIdentityListFromQualification(tempList, "system");
                
                log.info("考生[" + updatedData.getName() + ", 准考证号:" + updatedData.getExamNumber() 
                    + "]资格审查结果修改为'通过'，已自动流转到身份验证模块");
            }
            catch (Exception e)
            {
                log.error("自动流转到身份验证模块失败", e);
                // 不影响原有的更新操作，所以不抛出异常
            }
        }
        
        return rows;
    }

    /**
     * 批量删除四级联考资格审查
     * 
     * @param ids 需要删除的四级联考资格审查主键
     * @return 结果
     */
    @Override
    public int deleteQualificationManagementByIds(Long[] ids)
    {
        return qualificationManagementMapper.deleteQualificationManagementByIds(ids);
    }

    /**
     * 删除四级联考资格审查信息
     * 
     * @param id 四级联考资格审查主键
     * @return 结果
     */
    @Override
    public int deleteQualificationManagementById(Long id)
    {
        return qualificationManagementMapper.deleteQualificationManagementById(id);
    }

    /**
     * 导入四级联考资格审查数据
     * 
     * @param qualificationList 资格审查数据列表
     * @param updateSupport 是否更新支持，如果已存在，是否覆盖
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importQualificationData(List<QualificationManagement> qualificationList, boolean updateSupport, String operName)
    {
        // 终审结果表
        resultManagementMapper.deleteAllResultManagement();

        // 递补体能测试表
        dbPhysicalManagementMapper.deleteAllDbPhysicalManagement();

        // 递补身份验证表
        dbIdentityManagementMapper.deleteAllIdentityManagement();

        // 递补资格审查表
        dbQualificationManagementMapper.deleteAllDbQualificationManagement();

        // 体能测评表
        physicalManagementMapper.deleteAllPhysicalManagement();

        // 身份验证表
        identityManagementMapper.deleteAllIdentityManagement();

        // 资格审查表
        qualificationManagementMapper.deleteAllQualificationManagement();



        if (StringUtils.isNull(qualificationList) || qualificationList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (QualificationManagement qualification : qualificationList)
        {
            try
            {
                // 验证是否存在相同的准考证号或身份证号
                QualificationManagement existQualification = new QualificationManagement();
                if (StringUtils.isNotEmpty(qualification.getExamNumber()))
                {
                    existQualification.setExamNumber(qualification.getExamNumber());
                }
                else if (StringUtils.isNotEmpty(qualification.getIdCard()))
                {
                    existQualification.setIdCard(qualification.getIdCard());
                }
                else
                {
                    throw new ServiceException("导入数据中准考证号和身份证号不能同时为空");
                }
                
                List<QualificationManagement> existList = qualificationManagementMapper.selectQualificationManagementList(existQualification);
                
                if (StringUtils.isNull(existList) || existList.size() == 0)
                {
                    // 如果不存在，执行插入操作
                    qualificationManagementMapper.insertQualificationManagement(qualification);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + qualification.getExamNumber() + " 导入成功");
                }
                else if (updateSupport)
                {
                    // 如果存在且允许更新
                    qualification.setId(existList.get(0).getId()); // 设置ID，确保更新正确的记录
                    qualificationManagementMapper.updateQualificationManagement(qualification);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + qualification.getExamNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、准考证号 " + qualification.getExamNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、准考证号 " + qualification.getExamNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 从成绩合格名单生成并插入资格审查名单
     * 
     * @param scoreList 符合条件的成绩合格名单数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertQualificationListFromScore(List<ScoreManagement> scoreList, String operName)
    {
        if (StringUtils.isNull(scoreList) || scoreList.size() == 0)
        {
            throw new ServiceException("符合条件的考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 先清空现有资格审查名单数据
        QualificationManagement clearCriteria = new QualificationManagement();
        List<QualificationManagement> existingList = qualificationManagementMapper.selectQualificationManagementList(clearCriteria);
        if (existingList != null && existingList.size() > 0)
        {
            Long[] ids = new Long[existingList.size()];
            for (int i = 0; i < existingList.size(); i++)
            {
                ids[i] = existingList.get(i).getId();
            }
            qualificationManagementMapper.deleteQualificationManagementByIds(ids);
        }
        
        // 遍历符合条件的考生，插入资格审查名单
        for (ScoreManagement score : scoreList)
        {
            try
            {
                // 创建资格审查名单对象
                QualificationManagement qualification = new QualificationManagement();
                
                // 复制考生信息
                qualification.setCandidateId(score.getCandidateId());
                qualification.setName(score.getName());
                qualification.setGender(score.getGender());
                qualification.setIdCard(score.getIdCard());
                qualification.setExamNumber(score.getExamNumber());
                qualification.setAdministrativeAptitudeScore(score.getAdministrativeAptitudeScore());
                qualification.setEssayScore(score.getEssayScore());
                qualification.setProfessionalSubjectScore(score.getProfessionalSubjectScore());
                qualification.setTotalScore(score.getTotalScore());
                qualification.setProfessionalSkillTestScore(score.getProfessionalSkillTestScore());
                qualification.setAppliedUnit(score.getAppliedUnit());
                qualification.setAppliedPosition(score.getAppliedPosition());
                qualification.setRecruitmentNumber(score.getRecruitmentNumber());
                qualification.setInterviewRatio(score.getInterviewRatio());
                qualification.setRanking(score.getRanking());
                qualification.setGraduationSchool(score.getGraduationSchool());
                qualification.setHasProfessionalSkillTest(score.getHasProfessionalSkillTest());
                qualification.setPositionCategory(score.getPositionCategory());
                qualification.setIsAlternate(score.getIsAlternate());
//                qualification.setQualificationReviewResult("待审核");  // 默认为待审核
//                qualification.setIdentityVerificationResult("待验证");  // 默认为待验证
//                qualification.setPhysicalTestResult("待测评");  // 默认为待测评
//                qualification.setFinalResult("待确认");  // 默认为待确认
                
                // 执行插入操作
                qualificationManagementMapper.insertQualificationManagement(qualification);
                successNum++;
            }
            catch (Exception e)
            {
                log.error("插入资格审查名单失败，准考证号：" + score.getExamNumber(), e);
            }
        }
        
        return successNum;
    }

    /**
     * 生成身份验证名单
     * 从成绩合格名单过滤不通过考生，并按规则筛选
     *
     * @param operName 操作用户
     * @return 身份验证人数
     */
    @Override
    @Transactional
    public int generateIdentityList(String operName) {

        // 终审结果表
        resultManagementMapper.deleteAllResultManagement();

        // 递补体能测试表
        dbPhysicalManagementMapper.deleteAllDbPhysicalManagement();

        // 递补身份验证表
        dbIdentityManagementMapper.deleteAllIdentityManagement();

        // 递补资格审查表
        dbQualificationManagementMapper.deleteAllDbQualificationManagement();

        // 体能测评表
        physicalManagementMapper.deleteAllPhysicalManagement();

        // 身份验证表
        identityManagementMapper.deleteAllIdentityManagement();

        // 1. 获取所有成绩合格考生
        List<ScoreManagement> allScores = scoreManagementService.selectScoreManagementList(new ScoreManagement());

        // 2. 获取资格审查不通过的考生
        QualificationManagement failedCriteria = new QualificationManagement();
        failedCriteria.setQualificationReviewResult("未通过");
        List<QualificationManagement> failedQualifications = qualificationManagementMapper.selectQualificationManagementList(failedCriteria);

        // 3. 构建不通过考生标识集合（准考证号+身份证号）
        Set<String> failedIdentifiers = new HashSet<>();
        for (QualificationManagement q : failedQualifications) {
            failedIdentifiers.add(q.getExamNumber() + "_" + q.getIdCard());
        }

        // 4. 过滤有效考生
        List<ScoreManagement> validScores = allScores.stream()
                .filter(score -> !failedIdentifiers.contains(score.getExamNumber() + "_" + score.getIdCard()))
                .collect(Collectors.toList());

        // 5. 按单位+职位分组处理
        Map<String, List<ScoreManagement>> grouped = validScores.stream()
                .collect(Collectors.groupingBy(s -> s.getAppliedUnit() + "_" + s.getAppliedPosition()));

        List<ScoreManagement> finalCandidates = new ArrayList<>();

        for (Map.Entry<String, List<ScoreManagement>> entry : grouped.entrySet()) {
            List<ScoreManagement> group = entry.getValue();
            if (group.isEmpty()) continue;

            // 6. 获取职位参数
            ScoreManagement sample = group.get(0);
            Long recruitment = sample.getRecruitmentNumber();
            String ratioStr = sample.getInterviewRatio();
            boolean hasSkillTest = "是".equals(sample.getHasProfessionalSkillTest());

            // 7. 解析面试比例
            int ratio = 3;
            try {
                String[] ratioParts = ratioStr.split(":");
                if (ratioParts.length == 2) {
                    ratio = Integer.parseInt(ratioParts[1]);
                }
            } catch (Exception e) {
                log.error("面试比例解析错误：{}", ratioStr, e);
            }

            // 8. 排序逻辑
            group.sort((a, b) -> {
                if (hasSkillTest) {
                    return b.getProfessionalSkillTestScore().compareTo(a.getProfessionalSkillTestScore());
                } else {
                    return b.getTotalScore().compareTo(a.getTotalScore());
                }
            });

            // 9. 计算应录取人数
            int required = recruitment.intValue() * ratio;
            int actualCount = Math.min(required, group.size());
            if (actualCount == 0) continue;

            // 10. 处理同分考生
            BigDecimal baseScore = hasSkillTest ?
                    group.get(actualCount-1).getProfessionalSkillTestScore() :
                    group.get(actualCount-1).getTotalScore();

            for (int i = actualCount; i < group.size(); i++) {
                BigDecimal current = hasSkillTest ?
                        group.get(i).getProfessionalSkillTestScore() :
                        group.get(i).getTotalScore();

                if (current.compareTo(baseScore) == 0) {
                    actualCount++;
                } else {
                    break;
                }
            }

            // 11. 添加最终名单
            finalCandidates.addAll(group.subList(0, Math.min(actualCount, group.size())));
        }

        // 12. 转换为资格审查对象并插入
        return identityManagementService.insertIdentityListFromScore(finalCandidates, operName);
    }


    /**
     * 生成递补资格审查名单
     * 找出不合格考生职位，按照相同报考单位报考职位从成绩合格名单中递补考生
     * 
     * @param operName 操作用户
     * @return 递补人数
     */
    @Override
    @Transactional
    public int generateDbQualificationList(String operName)
    {
        // 查询所有资格审查不合格的考生
        QualificationManagement criteria = new QualificationManagement();
        // 设置查询条件：资格审查结果为"不通过"的考生
        criteria.setQualificationReviewResult("未通过");
        List<QualificationManagement> failedList = qualificationManagementMapper.selectQualificationManagementList(criteria);
        
        if (StringUtils.isNull(failedList) || failedList.size() == 0)
        {
            throw new ServiceException("没有资格审查不通过的考生，无需生成递补资格审查名单！");
        }
        
        // 按照报考单位和职位分组记录不合格考生
        java.util.Map<String, List<QualificationManagement>> failedGroups = new java.util.HashMap<>();
        
        for (QualificationManagement failed : failedList) {
            // 生成分组键：报考单位+报考职位
            String groupKey = failed.getAppliedUnit() + "_" + failed.getAppliedPosition();
            
            if (!failedGroups.containsKey(groupKey)) {
                failedGroups.put(groupKey, new java.util.ArrayList<>());
            }
            
            failedGroups.get(groupKey).add(failed);
        }
        
        // 获取成绩合格名单数据
        ScoreManagement scoreCriteria = new ScoreManagement();
        List<ScoreManagement> allScoreList = scoreManagementService.selectScoreManagementList(scoreCriteria);
        
        if (StringUtils.isNull(allScoreList) || allScoreList.size() == 0)
        {
            throw new ServiceException("成绩合格名单数据为空，无法生成递补资格审查名单！");
        }
        
        // 按照报考单位和职位分组成绩合格名单
        java.util.Map<String, List<ScoreManagement>> scoreGroups = new java.util.HashMap<>();
        
        for (ScoreManagement score : allScoreList) {
            // 生成分组键：报考单位+报考职位
            String groupKey = score.getAppliedUnit() + "_" + score.getAppliedPosition();
            
            if (!scoreGroups.containsKey(groupKey)) {
                scoreGroups.put(groupKey, new java.util.ArrayList<>());
            }
            
            scoreGroups.get(groupKey).add(score);
        }
        
        // 记录需要递补的考生
        List<ScoreManagement> dbCandidateList = new java.util.ArrayList<>();
        
        // 遍历不合格考生的分组
        for (String groupKey : failedGroups.keySet()) {
            List<QualificationManagement> failedCandidates = failedGroups.get(groupKey);
            
            // 获取对应职位的成绩合格考生
            List<ScoreManagement> scoreCandidates = scoreGroups.get(groupKey);
            
            if (scoreCandidates != null && scoreCandidates.size() > 0) {
                // 获取第一个不合格考生的信息，用于获取招考人数和面试比例
                QualificationManagement firstFailed = failedCandidates.get(0);
                
                // 获取职位的招考人数和面试比例
                Long recruitmentNumber = firstFailed.getRecruitmentNumber();
                String interviewRatio = firstFailed.getInterviewRatio();
                
                if (recruitmentNumber != null && StringUtils.isNotEmpty(interviewRatio)) {
                    // 解析面试比例，如 "1:3" 表示面试人数为招考人数的3倍
                    int ratio = 3; // 默认为3倍
                    try {
                        String[] parts = interviewRatio.split(":");
                        if (parts.length == 2) {
                            ratio = Integer.parseInt(parts[1]);
                        }
                    } catch (Exception e) {
                        log.error("解析面试比例出错：" + interviewRatio, e);
                    }
                    
                    // 计算需要参加资格审查的总人数
                    int requiredTotal = recruitmentNumber.intValue() * ratio;
                    
                    // 获取已经参加资格审查的考生数量（通过+不通过）
                    QualificationManagement allCriteria = new QualificationManagement();
                    allCriteria.setAppliedUnit(firstFailed.getAppliedUnit());
                    allCriteria.setAppliedPosition(firstFailed.getAppliedPosition());
                    List<QualificationManagement> allQualified = qualificationManagementMapper.selectQualificationManagementList(allCriteria);
                    
                    // 需要递补的人数 = 不合格考生数量
                    int needDbCount = failedCandidates.size();
                    
                    // 根据排名对成绩合格考生排序
                    scoreCandidates.sort((a, b) -> {
                        if (a.getRanking() == null && b.getRanking() == null) {
                            return 0;
                        }
                        if (a.getRanking() == null) {
                            return 1;
                        }
                        if (b.getRanking() == null) {
                            return -1;
                        }
                        return a.getRanking().compareTo(b.getRanking());
                    });
                    
                    // 筛选出已经在资格审查名单中的考生编号，避免重复递补
                    java.util.Set<String> existingExamNumbers = new java.util.HashSet<>();
                    for (QualificationManagement q : allQualified) {
                        existingExamNumbers.add(q.getExamNumber());
                    }
                    
                    // 从成绩合格名单中找出下一批排名的考生进行递补
                    int addedCount = 0;
                    ScoreManagement lastAddedScore = null;
                    
                    for (int i = 0; i < scoreCandidates.size(); i++) {
                        ScoreManagement score = scoreCandidates.get(i);
                        
                        if (addedCount < needDbCount && !existingExamNumbers.contains(score.getExamNumber())) {
                            dbCandidateList.add(score);
                            lastAddedScore = score; // 记录最后一个添加的考生
                            addedCount++;
                            
                            // 如果已经添加够了指定人数，检查是否有成绩相同的考生也需要一并添加
                            if (addedCount >= needDbCount && i + 1 < scoreCandidates.size()) {
                                // 获取是否增加专业技能测试的标志
                                String hasProfessionalSkillTest = score.getHasProfessionalSkillTest();
                                
                                // 检查后续考生是否与当前考生成绩相同
                                for (int j = i + 1; j < scoreCandidates.size(); j++) {
                                    ScoreManagement nextScore = scoreCandidates.get(j);
                                    
                                    // 如果下一个考生的准考证号已经在资格审查名单中，则跳过
                                    if (existingExamNumbers.contains(nextScore.getExamNumber())) {
                                        continue;
                                    }
                                    
                                    boolean scoresEqual = false;
                                    
                                    // 根据是否增加专业技能测试判断成绩是否相同
                                    if ("是".equals(hasProfessionalSkillTest)) {
                                        // 判断专业技能测试成绩是否相同
                                        if (score.getProfessionalSkillTestScore() != null && 
                                            nextScore.getProfessionalSkillTestScore() != null && 
                                            score.getProfessionalSkillTestScore().compareTo(nextScore.getProfessionalSkillTestScore()) == 0) {
                                            scoresEqual = true;
                                        }
                                    } else {
                                        // 判断总成绩是否相同
                                        if (score.getTotalScore() != null && 
                                            nextScore.getTotalScore() != null && 
                                            score.getTotalScore().compareTo(nextScore.getTotalScore()) == 0) {
                                            scoresEqual = true;
                                        }
                                    }
                                    
                                    // 如果成绩相同，则也添加到递补名单
                                    if (scoresEqual) {
                                        dbCandidateList.add(nextScore);
                                        log.info("考生[" + nextScore.getName() + ", 准考证号:" + nextScore.getExamNumber() 
                                            + "]由于成绩与递补最后一名相同，也被添加到递补资格审查名单");
                                    } else {
                                        // 一旦遇到不相同的成绩，后面的考生也不会相同，直接跳出循环
                                        break;
                                    }
                                }
                                
                                // 找完同分考生后，不再继续添加其他考生
                                break;
                            }
                        }
                    }
                }
            }
        }
        
        // 将筛选出的考生插入到递补资格审查名单
        int dbCount = 0;
        if (dbCandidateList.size() > 0) {
            dbCount = dbQualificationManagementService.insertDbQualificationListFromScore(dbCandidateList, operName);
        }
        
        return dbCount;
    }

    /**
     * 获取四级联考资格审查统计数据
     * 
     * @return 统计数据
     */
    @Override
    public StatisticsDTO getQualificationStatistics()
    {
        // 创建返回对象
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        
        // 查询所有资格审查数据
        List<QualificationManagement> qualificationList = qualificationManagementMapper.selectQualificationManagementList(new QualificationManagement());
        
        // 总数
        int total = qualificationList.size();
        statisticsDTO.setTotal(total);
        
        // 通过和未通过数量
        int passed = 0;
        // 职位分布统计
        Map<String, Integer> positionMap = new HashMap<>();
        
        for (QualificationManagement qualification : qualificationList)
        {
            // 统计通过人数
            if ("通过".equals(qualification.getQualificationReviewResult()))
            {
                passed++;
            }
            
            // 统计职位分布
            String position = qualification.getAppliedPosition();
            if (position != null && !position.isEmpty())
            {
                positionMap.put(position, positionMap.getOrDefault(position, 0) + 1);
            }
        }
        
        statisticsDTO.setPassed(passed);
        statisticsDTO.setFailed(total - passed);
        
        // 转换职位分布数据为前端所需格式
        List<PositionData> positionDataList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : positionMap.entrySet())
        {
            positionDataList.add(new PositionData(entry.getKey(), entry.getValue()));
        }
        statisticsDTO.setPositionData(positionDataList);
        
        return statisticsDTO;
    }
}
